package com.liush.system.controller;

import com.liush.common.helper.JwtHelper;
import com.liush.common.result.Result;
import com.liush.common.result.ResultCodeEnum;
import com.liush.common.util.MD5;
import com.liush.model.controller.SysUser;
import com.liush.model.vo.LoginVo;
import com.liush.system.exception.GuiguException;
import com.liush.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/admin/system/index")
@Api(tags = "后台登录管理")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;

    @ApiOperation("用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginVo loginVo) {
        /*System.out.println("用户名 = " + loginVo.getUsername());
        System.out.println("加密前密码 = " + loginVo.getPassword());
        System.out.println("加密后密码 = "+ MD5.encrypt(loginVo.getPassword()));
        // 查询用户名判断是否存在该用户
        SysUser sysUser = sysUserService.getByUserName(loginVo.getUsername());
        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        //用户存在，判断密码是否正确
        if (!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())) {
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        //该用户状态是否可用
        if (sysUser.getStatus().intValue() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // {"code":200,"data":{"token":"admin-token"}} 根据用户id、用户名生成令牌token
        Map<String,Object> map = new HashMap();
        map.put("token", JwtHelper.createToken(sysUser.getId(), sysUser.getUsername()));
        return Result.ok(map);*/
        return Result.ok();
    }

    @ApiOperation("获取信息")
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        // 通过 Jwt 解析 请求头的token(令牌) 获取 用户id
        Long userId = JwtHelper.getUserId(request.getHeader("token"));
        Map<String,Object> map = sysUserService.getUserInfoByUserId(userId);
        return Result.ok(map);
    }

    @ApiOperation("用户退出")
    @PostMapping("/logout")
    public Result logout() {
        return Result.ok();
    }

}
